# -*- conding:UTF-8 -*-

'''
@ Project: one-group
@ File: user.py
@ Author: 孙博
@ Date：2022/6/8 19:34

'''
from flask import Blueprint, jsonify, g
from flask_restful import reqparse, Resource, Api, marshal
from common.celery_tasks.send_code import send_message
from common.model_fileds.user import *
from models.user import *
from datetime import timedelta
from util.jwt_utils import genera_token
import redis
import random
from util.login_util import login_required
from util.qiniu_token import qiniu_token

user_bp = Blueprint('user_bp', __name__, url_prefix='/v1_0')

api = Api(user_bp)


class SendMessage(Resource):
    def post(self):
        redis_cli = redis.Redis(password='password')
        parser = reqparse.RequestParser()
        parser.add_argument('mobile')
        args = parser.parse_args()
        mobile = args['mobile']
        sms_code = random.randint(100000, 999999)
        res = send_message(mobile, sms_code)
        redis_cli.set(mobile, sms_code, ex=30000)
        if res:
            return jsonify(msg='发送成功，请注意查收', code=200)
        else:
            return jsonify(msg='发送失败，请稍后重试', code=400)


class Login(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('mobile')
        parser.add_argument('code')
        args = parser.parse_args()
        mobile = args['mobile']
        code = args['code']
        redis_cli = redis.Redis(password='password')
        sms_code = redis_cli.get(mobile).decode()
        if sms_code == code:
            try:
                user = UserModel.query.filter_by(mobile=mobile).first()
                print('user>>>', user)
                data = {
                    'user': user.uname,
                    'id': user.uid
                }
                expiry = timedelta(hours=2)
                token = genera_token(data, str(expiry))
                print('token>>>', token)
                if token:
                    datas = {
                        'user_id': user.uid,
                        'token': token
                    }
                    return jsonify(message='登录成功', code=200, data=datas)
                else:
                    return jsonify(message='token生成失败', code=500)

            except Exception as e:
                print('获取用户错误', e)
                return jsonify(msg='此手机号未注册', code=400)


class ChannelsView(Resource):
    @login_required
    def get(self):
        channels = Channel.query.all()
        data = marshal(channels, channel_fields)
        print('data>>>>>', data)
        return data


class ChannelTitle(Resource):
    @login_required
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('channel_id')
        args = parser.parse_args()
        channel_id = args['channel_id']
        print('>>>>>>', channel_id)
        news = News.query.filter_by(channel_id=channel_id).all()
        data = marshal(news, news_fields)
        return data


class OneChannelTitle(Resource):
    def get(self, id):
        news = News.query.filter_by(nid=id).first()
        data = marshal(news, news_fields)
        return data


class CommentsView(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('source')
        args = parser.parse_args()
        nid = args['source']
        print('前端传来的id>>>>', nid)
        comments1 = Comment.query.filter_by(article_id=nid, parent_id=None).all()
        comment1_list = []
        for i in comments1:
            comment1 = marshal(i, comments_fields)
            user = UserModel.query.filter_by(uid=i.user_id).first()
            comments2 = Comment.query.filter_by(parent_id=i.cmid).all()
            comment2_list = []
            for j in comments2:
                comment2 = marshal(j, comments_fields)
                user = UserModel.query.filter_by(uid=j.user_id).first()
                comment2['user2'] = marshal(user, user_fields)
                comment2_list.append(comment2)
            comment1['parent'] = comment2_list
            comment1['user1'] = marshal(user, user_fields)
            comment1_list.append(comment1)
            # print('>>>>>>', comment1_list)
        return jsonify(data=comment1_list)


# 发布评论
class SendComments(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('target')
        parser.add_argument('content')
        parser.add_argument('parent_id')
        args = parser.parse_args()
        nid = args['target']
        content = args['content']
        parent_id = args['parent_id']
        print('parent_id>>>>', parent_id)
        uid = g.user_id
        print('uid>>>>>', g.user_id)
        if not parent_id:
            comments = Comment(user_id=uid, article_id=nid, content=content)
            db.session.add(comments)
            db.session.commit()
            return jsonify(message='发布成功', code=200)
        else:
            comments = Comment(user_id=uid, article_id=nid, content=content, parent_id=parent_id)
            db.session.add(comments)
            db.session.commit()
            return jsonify(message='发布成功', code=200)


class UserMessage(Resource):
    def get(self):
        uid = g.user_id
        user = UserModel.query.filter_by(uid=uid).first()
        data = marshal(user, user_fields)
        print('用户信息>>>>', data)
        return data


class ChangeUser(Resource):
    def patch(self):
        parser = reqparse.RequestParser()
        parser.add_argument('name')
        parser.add_argument('birthday')
        parser.add_argument('gender')
        parser.add_argument('profile_photo')
        args = parser.parse_args()
        name = args['name']
        ctime = args['birthday']
        gender = args['gender']
        profile_photo = args['profile_photo']
        uid = 1
        print('name是%s, ctime是%s, gender是%s' % (name, ctime, gender))
        if name:
            try:
                UserModel.query.filter_by(uid=uid).update({'uname': name})
                db.session.commit()
                print('名字修改成功')
            except Exception as e:
                print(e)
                return e
        if ctime:
            try:
                UserModel.query.filter_by(uid=uid).update({'created_time': ctime})
                db.session.commit()
                print('生日修改成功')
            except Exception as e:
                print(e)
                return e
        if gender:
            if gender == 1:
                UserModel.query.filter_by(uid=uid).updata({'gender': 0})
                db.session.commit()
            else:
                UserModel.query.filter_by(uid=uid).update({'gender': 1})
                db.session.commit()
        if profile_photo:
            UserModel.query.filter_by(uid=uid).update({'profile_photo': profile_photo})
            db.session.commit()


class QiNiu_Token(Resource):
    def get(self):
        token = qiniu_token()
        print('七牛云token>>>>', token)
        return jsonify(message='ok', code=200, data={'token': token})


api.add_resource(SendMessage, '/sms_code')
api.add_resource(Login, '/login')
api.add_resource(ChannelsView, '/channels')
api.add_resource(ChannelTitle, '/articles')
api.add_resource(OneChannelTitle, '/articles/<int:id>')
api.add_resource(CommentsView, '/comments')
api.add_resource(SendComments, '/comments')
api.add_resource(UserMessage, '/profile')
api.add_resource(ChangeUser, '/user/profile')
api.add_resource(QiNiu_Token, '/qiniu_token')
